<template>
    <div class="operationBasicsDetail">
        <div class="header">
     
            <van-nav-bar title="添加品牌" left-text="" left-arrow @click-left="goBack" />
        </div>
        <div class="add_brand">
            <van-form @submit="onSubmit" validate-first scroll-to-error>
                <van-cell-group inset>
                    <van-field name="brandName" required label="品牌名称" v-model="addBrandQualificationQueryParams.brandName" placeholder="请输入"
                        input-align="right" error-message-align="right" :maxlength="50" :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入品牌名称' },
                            {
                                validator: validatorNumber,
                                message: '请输入正确的品牌名称',
                            },
                        ]" />
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="品牌商标注册证" label="品牌商标注册证" input-align="right" error-message-align="right">
                        <template #input>
                            <div class="value">
                                <div v-for="(item, index) in brandImageList" :key="index" class="imgList">
                                    <div class="loading_pic" v-if="!item.url">
                                        <van-loading type="spinner" size="20" />
                                    </div>
                                    <van-image :src="item.url + '?x-oss-process=image/resize,w_300'"
                                        @click="enlargeImage(item.url)" v-if="item.url"></van-image>
                                    <van-icon name="cross" color="#fff" v-if="item.url"
                                        @click.prevent="deleteImg(brandImageList, index, 'brandImage')" />
                                </div>
                                <van-image :src="upload" v-if="brandImageList.length < 1" @click="postImage('brandImage')"
                                    v-throttle:click></van-image>
                            </div>

                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="商标授权使用证明" label="商标授权使用证明" input-align="right" error-message-align="right">
                        <template #input>
                            <div class="value">
                                <div v-for="(item, index) in usageImageList" :key="index" class="imgList">
                                    <div class="loading_pic" v-if="!item.url">
                                        <van-loading type="spinner" size="20" />
                                    </div>
                                    <van-image :src="item.url + '?x-oss-process=image/resize,w_300'"
                                        @click="enlargeImage(item.url)" v-if="item.url"></van-image>
                                    <van-icon name="cross" color="#fff" v-if="item.url"
                                        @click.prevent="deleteImg(usageImageList, index, 'usageImage')" />
                                </div>
                                <van-image :src="upload" v-if="usageImageList.length < 1" @click="postImage('usageImage')"
                                    v-throttle:click></van-image>
                            </div>

                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="usages" label="使用授权品类" v-model="addBrandQualificationQueryParams.usages" is-link readonly placeholder="请选择"
                        input-align="right" error-message-align="right" @click="showUsageCategory = true" />
                    <van-popup v-model:show="showUsageCategory" position="bottom">
                        <van-picker :columns="usageCategoryColumns" @confirm="onConfirmUsageCategory"
                            @cancel="showUsageCategory = false">
                            <template #option="option">
                                <div style="width: 100%">
                                    <van-checkbox-group v-model="usages" style="display: inline-block; margin-left: 130px">
                                        <van-checkbox :name="option.text" shape="square">{{
                                            option.text
                                            }}</van-checkbox>
                                    </van-checkbox-group>
                                </div>
                            </template>
                        </van-picker>
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="店铺销售授权" label="店铺销售授权" input-align="right" error-message-align="right">
                        <template #input>
                            <div class="value">
                                <div v-for="(item, index) in sellImageList" :key="index" class="imgList">
                                    <div class="loading_pic" v-if="!item.url">
                                        <van-loading type="spinner" size="20" />
                                    </div>
                                    <van-image :src="item.url + '?x-oss-process=image/resize,w_300'"
                                        @click="enlargeImage(item.url)" v-if="item.url"></van-image>
                                    <van-icon name="cross" color="#fff" v-if="item.url"
                                        @click.prevent="deleteImg(sellImageList, index, 'sellImage')" />
                                </div>
                                <van-image :src="upload" v-if="sellImageList.length < 1" @click="postImage('sellImage')"
                                    v-throttle:click></van-image>
                            </div>

                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="sells" label="销售授权品类" v-model="addBrandQualificationQueryParams.sells" is-link readonly placeholder="请选择"
                        input-align="right" error-message-align="right" @click="showSellCategory = true" />
                    <van-popup v-model:show="showSellCategory" position="bottom">
                        <van-picker :columns="sellCategoryColumns" @confirm="onConfirmSellCategory"
                            @cancel="showSellCategory = false">
                            <template #option="option">
                                <div style="width: 100%">
                                    <van-checkbox-group v-model="sells" style="display: inline-block; margin-left: 130px">
                                        <van-checkbox :name="option.text" shape="square">{{
                                            option.text
                                            }}</van-checkbox>
                                    </van-checkbox-group>
                                </div>
                            </template>
                        </van-picker>
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="其他补充资质" label="其他补充资质" input-align="right" error-message-align="right">
                        <template #input>
                            <div class="value">
                                <div v-for="(item, index) in otherImageList" :key="index" class="imgList">
                                    <div class="loading_pic" v-if="!item.url">
                                        <van-loading type="spinner" size="20" />
                                    </div>
                                    <van-image :src="item.url + '?x-oss-process=image/resize,w_300'"
                                        @click="enlargeImage(item.url)" v-if="item.url"></van-image>
                                    <van-icon name="cross" color="#fff" v-if="item.url"
                                        @click.prevent="deleteImg(otherImageList, index, 'otherImage')" />
                                </div>
                                <van-image :src="upload" v-if="otherImageList.length < 1" @click="postImage('otherImage')"
                                    v-throttle:click></van-image>
                            </div>

                        </template>
                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="联名款/其他授权" label="联名款/其他授权" input-align="right" error-message-align="right">
                        <template #input>
                            <div class="value">
                                <div v-for="(item, index) in jointlyImageList" :key="index" class="imgList">
                                    <div class="loading_pic" v-if="!item.url">
                                        <van-loading type="spinner" size="20" />
                                    </div>
                                    <van-image :src="item.url + '?x-oss-process=image/resize,w_300'"
                                        @click="enlargeImage(item.url)" v-if="item.url"></van-image>
                                    <van-icon name="cross" color="#fff" v-if="item.url"
                                        @click.prevent="deleteImg(jointlyImageList, index, 'jointlyImage')" />
                                </div>
                                <van-image :src="upload" v-if="jointlyImageList.length < 1"
                                    @click="postImage('jointlyImage')" v-throttle:click></van-image>
                            </div>

                        </template>
                    </van-field>
                </van-cell-group>
                <div class="addtive_div-btn">
                    <van-button round block  class="addtive_div" :loading="loading"  loading-text="执行中..." type="primary" native-type="submit" v-throttle:click>
                        保存
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>
<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { addBrand } from '@/api/supplierList/index'
import { getDicts } from '@/api/productList/index'
import { showSuccessToast,showFailToast } from 'vant';
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { showImagePreview } from 'vant';
import { getEnvValue } from "@/utils/index";
import { handleImageUpdate } from '@/utils/handleImageUpdate';
const upload = new URL('@/assets/home/upload.png', import.meta.url).href
const store = loginStore();
const { token } = storeToRefs(store);
const route = useRoute()
const router = useRouter()
/** 商品id */
const uniquekey = computed(() => {
    return route.params.id
})
const loading = ref(false)
const usages = ref<any[]>([]);
const sells = ref<any[]>([])
const showUsageCategory = ref(false)
const usageCategoryColumns = ref([])
const showSellCategory = ref(false)
const sellCategoryColumns = ref([])
const addBrandQualificationQueryParams = ref({
    brandName: '',
    brandImage: [],
    usageImage: [],
    usages: '',
    sellImage: [],
    sells: '',
    otherImage: [],
    jointlyImage: []
})
const brandImageList = ref<any[]>([])
const usageImageList = ref<any[]>([])
const sellImageList = ref<any[]>([])
const otherImageList = ref<any[]>([])
const jointlyImageList = ref<any[]>([])

const validatorNumber = (val) => /^[\u0020-\u007e\u4e00-\u9fa5]+$/.test(val);

/** 使用授权品类 */
const getSupplierType = async () => {
    const res = await getDicts('hm_trademark')
    res.data.forEach(element => {
        element.text = element.dictLabel
        element.value = element.dictValue
    })
    usageCategoryColumns.value = res.data
}
getSupplierType()
/**使用授权品类关闭 */
const onConfirmUsageCategory = () => {
    addBrandQualificationQueryParams.value.usages = usages.value.join(',');
    showUsageCategory.value = false;
}

/** 销售授权品类 */
const getsellCategory = async () => {
    const res = await getDicts('hm_trademark')
    res.data.forEach(element => {
        element.text = element.dictLabel
        element.value = element.dictValue
    })
    sellCategoryColumns.value = res.data
}
getsellCategory()
/**销售授权品类关闭 */
const onConfirmSellCategory = () => {
    addBrandQualificationQueryParams.value.sells = sells.value.join(',')
    showSellCategory.value = false;
}


/** 离开页面、提交移除本地存储 */
const removeLocal = () => {
    // 删除app切换导致得缓存数据问题 清除
    localStorage.removeItem('addBrandQualificationQueryParams')
    brandImageList.value && localStorage.removeItem('brandImageList')
    usageImageList.value && localStorage.removeItem('usageImageList')
    sellImageList.value && localStorage.removeItem('sellImageList')
    otherImageList.value && localStorage.removeItem('otherImageList')
    jointlyImageList.value && localStorage.removeItem('jointlyImageList')
    addBrandQualificationQueryParams.value = {
        brandName: '',
        brandImage: [],
        usageImage: [],
        usages: '',
        sellImage: [],
        sells: '',
        otherImage: [],
        jointlyImage: []
    }
    brandImageList.value = []
    usageImageList.value = []
    sellImageList.value = []
    otherImageList.value = []
    jointlyImageList.value = []
}
/**
 * 图片全路径转半路径
 * @param list 
 */
 const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
const onSubmit = async () => {
    loading.value = true
    try{
        const list = JSON.parse(JSON.stringify(addBrandQualificationQueryParams.value))
        list.brandImage = getPicByfullPath(brandImageList.value)
        list.usageImage = getPicByfullPath(usageImageList.value)
        list.sellImage = getPicByfullPath(sellImageList.value)
        list.otherImage = getPicByfullPath(otherImageList.value)
        list.jointlyImage = getPicByfullPath(jointlyImageList.value)
        list.supplierId = uniquekey.value
        // 测试
        await addBrand(list)
        loading.value = false
        showSuccessToast({ type: 'success', message: '添加品牌成功' });
        removeLocal();
        router.back()
    }catch (error) {
        if(error=='timeout'){
        showFailToast('添加品牌失败');
        }
        loading.value = false
    }
}
/** app端隐藏触发保存表单 */
(window as any).saveState = function (arg) {
    if (arg.action == 'save') {
        localStorage.setItem("addBrandQualificationQueryParams", JSON.stringify(addBrandQualificationQueryParams.value));
        if (brandImageList.value.length > 0) {
            localStorage.setItem("brandImageList", JSON.stringify(brandImageList.value));
        }
        if (usageImageList.value.length > 0) {
            localStorage.setItem("usageImageList", JSON.stringify(usageImageList.value));
        }
        if (sellImageList.value.length > 0) {
            localStorage.setItem("sellImageList", JSON.stringify(sellImageList.value));
        }
        if (otherImageList.value.length > 0) {
            localStorage.setItem("otherImageList", JSON.stringify(otherImageList.value));
        }
        if (jointlyImageList.value.length > 0) {
            localStorage.setItem("jointlyImageList", JSON.stringify(jointlyImageList.value));
        }
    }
}
onUnmounted(() => {
    removeLocal();
})
/** app端重新打开后数据保存重新渲染 */
const rendering = () => {
    if (localStorage.getItem('addBrandQualificationQueryParams')) {
        addBrandQualificationQueryParams.value = JSON.parse(localStorage.getItem('addBrandQualificationQueryParams') as string)
    }
    if (localStorage.getItem('brandImage')) {
        brandImageList.value = JSON.parse(localStorage.getItem('brandImageList') as string)
    }
    if (localStorage.getItem('usageImage')) {
        usageImageList.value = JSON.parse(localStorage.getItem('usageImageList') as string)
    }
    if (localStorage.getItem('sellImage')) {
        sellImageList.value = JSON.parse(localStorage.getItem('sellImageList') as string)
    }
    if (localStorage.getItem('otherImage')) {
        otherImageList.value = JSON.parse(localStorage.getItem('otherImageList') as string)
    }
    if (localStorage.getItem('jointlyImage')) {
        jointlyImageList.value = JSON.parse(localStorage.getItem('jointlyImageList') as string)
    }
}
rendering()
/** 删除 */
const deleteImg = (list: any, index: number, res: string) => {
    list.splice(index, 1);
    const reslist = res.split(',')
    reslist.splice(index, 1)
    addBrandQualificationQueryParams.value[res] = reslist.join(',')
}
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img]
        })
    }
}
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        brandImage: brandImageList.value,
        usageImage: usageImageList.value,
        sellImage: sellImageList.value,
        otherImage: otherImageList.value,
        jointlyImage: jointlyImageList.value,
    };

    const maxCounts = {
        brandImage: 1,
        usageImage: 1,
        sellImage: 1,
        otherImage: 1,
        jointlyImage: 1,
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);

}
const postImage = (name: string) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: 'img',
            count: 1,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e'
            }
        }
    })
}
/** 返回上一页 */
const goBack = () => {
  router.back()
}
</script>
<style lang="less" scoped>
:deep(.van-field__label) {
  width: 120px;
}
.add_brand {
    background-color: #f6faff;
    width: 100%;
    height: calc(100vh - 90px);
    box-sizing: border-box;
    padding: 10px 15px 94px 15px;
    margin-top: 90px;
    overflow-y: scroll;
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-form) {
    // height: 100%;
    background-color: #fff;
    // padding-bottom: 35px !important;
}

.value {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;

    .imgList {
        position: relative;

        .loading_pic {
            width: 90px;
            height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :deep(.van-image__img) {
            margin-right: 5px;
        }

        :deep(.van-icon) {
            position: absolute;
            top: 0;
            z-index: 100;
            right: 4px;
            font-size: 10px;
            height: 15px;
            width: 15px;
            background-color: #000;
            border-bottom-left-radius: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        :deep(.van-icon-cross:before) {
            margin: 0 0 1px 2px;
        }
    }



    :deep(.van-image__img) {
        width: 77px;
        height: 77px;
    }

}

:deep(.van-field__control) {
    color: #B8BECA !important;
}

:deep(.van-icon-arrow:before) {
    color: #B8BECA !important;
}

:deep(.van-cell) {
    align-items: center;
}
.operationBasicsDetail {
  width: 100%;
  // height: 100vh;
  background: #f6faff;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-content: flex-start;

  .header {
    background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
    filter: blur(0px);
    height: 90px;
    padding-top: 44px;
    box-sizing: border-box;
    width: 100%;
    position: fixed;
    z-index: 6003;

    :deep(.van-icon-arrow-left) {
      color: #1a1b1c !important;
    }

    :deep(.van-nav-bar) {
      background: none !important;
    }

    :deep(.van-nav-bar__content) {
      background-color: transparent !important;
    }
  }

}
:deep(.van-cell-group--inset) {
  margin: 0 !important;
  border-radius: 0 !important;
}

:deep(.van-form) {
  // height: 100%;
  // overflow-y: scroll;
  background-color: #fff;
  // padding-bottom: 35px !important;
}
:deep(.van-field--disabled){
  background-color: #f3f3f3;
  .van-field__control{
    color: #8492AD !important;
    -webkit-text-fill-color:#8492AD !important;
  }
  div[aria-checked=true] .van-radio__icon{
    color: #0094FF !important;
    -webkit-text-fill-color: #0094FF !important;
  }
}
:deep(.van-cell) {
      padding: 20px 15px;
      position: relative;
      &::after{
         content: "";
         display: block;
         height: 2px;
         width: 315px;
         background-color: #F3F3FF;
      }
      
      
  }
  :deep(.van-cell-group):last-child{

      .van-cell{
          border-bottom: none !important;
      }
      
  }
  :deep(.van-field__label) {
    
      color: #464E5D  !important;
  }

  :deep(.van-field__label--required){
      &::before{
          display: none;
      }
      &::after{
          color: var(--van-field-required-mark-color);
          content: "*";
      }
  }
  .imgform{
    :deep(.van-cell) {
        border-bottom: none !important;
        &::after{
            content: none;
        }
    }
  }
.addtive_div-btn {
    position: fixed;
    width: 100%;
    height: 84px;
    bottom: 0;
    left: 0;
    z-index: 110;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(189,195,204,0.5);
    box-sizing: border-box;
    padding: 0 15px;
    // padding-bottom: 120px;
    .addtive_div {
        width: 320px;
        height: 44px;
        text-align: center;
        margin: auto;
        //   margin-top: 200px;
       
    }
}
</style>